from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from modules.system.schemas.auth_schemas import LoginRequest, RefreshRequest
from modules.system.vos.auth_vo import TokenPair
from modules.system.services.auth_service import AuthService
from core.base.api_mode import ApiResponse, api_success, api_error

router = APIRouter()


@router.post("/login", response_model=ApiResponse[TokenPair], summary="用户登录")
async def login(payload: LoginRequest, db: AsyncSession = Depends(get_db)):
    user = await AuthService.authenticate(db, payload.username, payload.password)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户名或密码错误")
    tokens = await AuthService.issue_tokens(user)
    return api_success(TokenPair(access_token=tokens["access_token"], refresh_token=tokens["refresh_token"]), msg="登录成功")


@router.post("/refresh", response_model=ApiResponse[TokenPair], summary="刷新令牌")
async def refresh_tokens(payload: RefreshRequest):
    try:
        tokens = await AuthService.refresh_tokens(payload.refresh_token)
        return api_success(TokenPair(access_token=tokens["access_token"], refresh_token=tokens["refresh_token"]), msg="刷新成功")
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))